<template>
  <el-dialog class="public-dialog" title="导入" :modelValue="dialogVisible" align-center width="560" @close="handleClose" :close-on-click-modal="false">
    <p class="text-[14px] leading-[20px] mb-[8px]">第 <span class="font-[600]">1</span> 步：点击下载模版</p>
    <a :href="downloadUrl" class="bg-[#FAFAFA] flex items-center justify-center rounded-[4px] py-[12px] cursor-pointer">
      <div class="text-[#3366F1] flex items-center gap-1">
        <div class="dk-iconfont icon-Download"></div>
        下载模板
      </div>
    </a>
    <p class="text-[14px] leading-[20px] my-[16px]">第 <span class="font-[600]">2</span> 步：按照模版要求填写</p>
    <p class="text-[14px] leading-[20px] mb-[8px]">第 <span class="font-[600]">3</span> 步：上传填写完成的文件</p>
    <el-upload
      ref="upload"
      v-model:file-list="fileList"
      accept=".csv,.xml,.xlsx"
      class="v-import"
      drag
      :data="extraData"
      :action="ossParams.host ? `${ossParams.host}` : ''"
      :limit="1"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
    >
      <div class="text-[#3366F1] flex items-center">
        <div class="dk-iconfont icon-Plus"></div>
        上传文件
      </div>
    </el-upload>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loadings.submit" :disabled="!fileList.length" @click="submit"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from "./api"

import { ElMessage, ElMessageBox, genFileId, ElNotification } from "element-plus"
import { ref } from "vue"
const load = ref(false)

import { uploadSignUrl } from "@/api/public"

const dialogVisible = ref(false)
const downloadUrl = ref("")

const props = defineProps({
  // callBack: {
  //   type: Function,
  //   default: (query) => query,
  // },
  tpl_name: { type: String, default: "" },
  oss_key: { type: String, default: "" },
  imporApi: { type: Function, default: () => {} },
  // downloadUrl: { type: String, default: "" },
  // tableRef: { type: Object, default: () => ({}) },
  // task: Boolean,
})

let loadings = reactive({})
let ossParams = reactive({
  host: "",
})

const emit = defineEmits(["close"])

const fileList = ref([])
const upload = ref()
const extraData = reactive({})
const uploadPercent = ref(0)
const fileName = ref("")

const handleExceed = (files) => {
  upload.value?.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value?.handleStart(file)
}

const get_suffix = (name) => {
  const pos = name.lastIndexOf(".")
  let suffix = ""
  if (pos != -1) {
    suffix = name.substring(pos)
  }
  return suffix
}

const beforeUpload = async (file) => {
  if (file.size > 1024 * 1024 * 1024) {
    ElMessage.warning("上传文件大小不能超过1G")
    return false
  }

  uploadPercent.value = 0
  try {
    const { policy, accessid, dir, signature } = ossParams || {}
    const name = `${file.name.split(".")[0]}_${new Date().getTime()}`
    const _fileName = name + get_suffix(file.name)
    extraData.key = dir + _fileName
    extraData.policy = policy
    extraData.OSSAccessKeyId = accessid
    extraData.signature = signature
    extraData.oss_url = `${props.oss_key}${_fileName}`
    fileName.value = _fileName
    return true
  } catch (err) {
    fileName.value = ""
    ElMessage.error(err.message)
    return false
  }
}

const handleUploadSuccess = () => {
  // console.error("ar", arguments)
  props.imporApi({ oss_url: extraData.oss_url }).then((res) => {
    ElMessage({ type: "success", message: `上传成功` })
    handleClose()
  })
}

const handleUploadError = (err) => {
  fileName.value = ""
  ElMessage.error(`上传失败 ${err.toString()}`)
  uploadPercent.value = 0
}
// 打开弹窗
const open = async () => {
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  loadings.submit = false
  fileList.value = []
}

// 提交
const submit = async () => {
  loadings.submit = true
  await initUpload()
  upload.value.submit()
}
const initUpload = async () => {
  const { data } = await uploadSignUrl({ dir: props.oss_key })
  ossParams = { ...data?.signature }
}

onMounted(() => {
  initUpload()
  getTemmplate()
})
const getTemmplate = async () => {
  const { tpl_name } = props
  const res = await api.getImportTpl({ tpl_name })
  downloadUrl.value = res.data.url
}

defineExpose({
  open,
  handleClose,
})
</script>

<style lang="scss" scoped>
.v-import {
  :deep(.el-upload-dragger) {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-color: #3366f1;
  }
}
</style>
